package com.example.springboot2022nocv.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.springboot2022nocv.entity.User;
import com.example.springboot2022nocv.service.UserService;
import com.example.springboot2022nocv.vo.DataView;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.Subject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    //获取验证码
    @RequestMapping("/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session)throws IOException {
        //验证码对象 HuTool定义图形验证码的长和宽,验证码的位数,干扰线的条数
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha( 116,36,4,10);
        //2.放入到session
        session.setAttribute("code" ,captcha.getCode());
        //3.输出验证码
        ServletOutputStream outputstream = response.getOutputStream();
        captcha.write(outputstream);
        //4关闭输出流
        outputstream.close();
    }
    //具体的登录逻辑
    @RequestMapping("/login/login")
    @ResponseBody
    public DataView login(String loginname,String pwd,String code,HttpSession session){
        DataView dataView = new DataView();
        // 1.首先判断验证码对不对
        String sessionCode = (String)session.getAttribute("code");
        if (code != null && sessionCode.equals(code)){
            // 2.登录逻辑
            User user = userService.login(loginname,pwd);
            // 3．判断
            if (user!=null){
                dataView.setCode(200);
                dataView.setMsg("登录成功!");
                session.setAttribute("user",user);
                return dataView;
            }else {
                dataView.setCode(100);
                dataView. setMsg("用户名或者密码错误，登陆失败!");
                return dataView;
            }
        }
        dataView.setCode( 300);
        dataView. setMsg("验证码错误!");
        return dataView;
    }

    @RequestMapping("login/logout")
    public String logout(){
        return "login";
    }
}
